package com.screen.screendisplay.service.impl.ne;

import com.screen.screendisplay.entity.ne.NeProdoperPowerTotal;
import com.screen.screendisplay.mapper.ne.NeProdoperPowerTotalMapper;
import com.screen.screendisplay.service.ne.NeProdoperPowerTotalService;
import com.screen.screendisplay.vo.ne.NePowerGenerationYoyVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 新能源总发电量同比率统计表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeProdoperPowerTotalServiceImpl extends ServiceImpl<NeProdoperPowerTotalMapper, NeProdoperPowerTotal> implements NeProdoperPowerTotalService {

    @Autowired
    private NeProdoperPowerTotalMapper neProdoperPowerTotalMapper;

    @Override
    public List<NePowerGenerationYoyVO> getPowerGenerationYoyRate(Integer year) {
        List<NeProdoperPowerTotal> dataList = neProdoperPowerTotalMapper.selectMonthlyYoyData(6);
        return dataList.stream().map(data -> {
            NePowerGenerationYoyVO vo = new NePowerGenerationYoyVO();
            vo.setYear(data.getYear());
            vo.setMonth(data.getMonth());
            vo.setCurrentYearGeneration(data.getActualGeneration());
            
            // 将字符串转换为BigDecimal
            BigDecimal lastYearGeneration = new BigDecimal(data.getLastYearActualGeneration());
            vo.setLastYearGeneration(lastYearGeneration);
            
            // 计算同比率：((当年 - 去年) / 去年) * 100
            if (lastYearGeneration.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal yoyRate = data.getActualGeneration().subtract(lastYearGeneration)
                                   .divide(lastYearGeneration, 4, RoundingMode.HALF_UP)
                                   .multiply(new BigDecimal(100))
                                   .setScale(2, RoundingMode.HALF_UP);
                vo.setYoyRate(yoyRate);
            } else {
                vo.setYoyRate(BigDecimal.ZERO);
            }
            
            return vo;
        }).collect(Collectors.toList());
    }
}
